import React, { Component } from "react";

import Form from "./Form";
import List from "./List";

class App extends Component {
  state = {
    list: [
      {
        id: 1,
        name: "zhangsan",
        checked: false,
      },
      {
        id: 2,
        name: "kunkun",
        checked: false,
      },
    ],
  };

  add = (val) => {
    // console.log("add");
    this.setState({
      list: [
        ...this.state.list,
        { id: new Date().getTime(), name: val, checked: false },
      ],
    });
  };

  remove = (id) => {
    // console.log("remove", id);
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    });
  };

  change = (id, bool) => {
    // this.state.list[i].checked = bool;
    // this.setState({});
    this.setState(
      {
        list: this.state.list.map((item) => {
          if (item.id === id) {
            return {
              ...item,
              checked: bool,
            };
          } else {
            return item;
          }
        }),
      },
      () => {
        console.log(this.state.list);
      }
    );
  };

  removeAll = () => {
    // console.log("removeAll");
    this.setState({
      list: this.state.list.filter((item) => {
        return !item.checked;
      }),
    });
  };

  render() {
    return (
      <>
        <h2>todolist</h2>

        <Form onAdd={this.add} />
        <List
          list={this.state.list}
          onRemove={this.remove}
          onCheckChange={this.change}
          onRemoveAll={this.removeAll}
        />
      </>
    );
  }
}

export default App;
